package com.example.arithmeticleetcode.leetcode;

import java.util.*;

/**
 * @program: arithmetic-leetcode
 * @description: 1394. 找出数组中的幸运数
 * @author: FangZhen
 * @create: 2020-04-16 09:44
 **/
public class Demo02 {

    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 3, 3, 3};
        System.out.println(findLucky01(arr));
    }

    public static int findLucky01(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>(arr.length);
        for (int i : arr) {
            if (!map.containsKey(i)) {
                map.put(i, 1);
            } else {
                int count = map.get(i);
                map.put(i, ++count);
            }
        }
        List<Integer> list = new ArrayList<>();
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getKey() == entry.getValue()) {
                list.add(entry.getKey());
            }
        }
        int result = -1;
        for (Integer num : list) {
            if (result < num) {
                result = num;
            }
        }
        return result;
    }

    public static int findLucky02(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        int max = Integer.MIN_VALUE;
        for (int i : arr) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        for (Integer num : map.keySet()) {
            if (map.get(num) == num) max = Math.max(max, num);
        }
        return max == Integer.MIN_VALUE ? -1 : max;
    }
}
